// 从 localStorage 获取初始值
const getLocalStorageItem = (key, defaultValue) => {
  const item = localStorage.getItem(key)
  return item ? JSON.parse(item) : defaultValue
}

const state = {
  subjects: getLocalStorageItem('subjects', [
    '语文', '数学', '英语', '物理', '化学', '生物', '政治', '历史', '地理'
  ]),
  grades: getLocalStorageItem('grades', [
    '必修一',
    '必修二',
    '必修三',
    '选择性必修一',
    '选择性必修二',
    '选择性必修三',
    '选择性必修四'
  ]),
  channels: getLocalStorageItem('channels', ['新华书店', '大众书店', '文轩书店', '其他'])
}

const mutations = {
  SET_SUBJECTS(state, subjects) {
    state.subjects = subjects
    localStorage.setItem('subjects', JSON.stringify(subjects))
  },
  SET_GRADES(state, grades) {
    state.grades = grades
    localStorage.setItem('grades', JSON.stringify(grades))
  },
  SET_CHANNELS(state, channels) {
    state.channels = channels
    localStorage.setItem('channels', JSON.stringify(channels))
  },
  ADD_SUBJECT(state, subject) {
    if (!state.subjects.includes(subject)) {
      state.subjects.push(subject)
      localStorage.setItem('subjects', JSON.stringify(state.subjects))
    }
  },
  ADD_GRADE(state, grade) {
    if (!state.grades.includes(grade)) {
      state.grades.push(grade)
      localStorage.setItem('grades', JSON.stringify(state.grades))
    }
  },
  ADD_CHANNEL(state, channel) {
    if (!state.channels.includes(channel)) {
      state.channels.push(channel)
      localStorage.setItem('channels', JSON.stringify(state.channels))
    }
  }
}

const actions = {
  updateSubjects({ commit }, subjects) {
    commit('SET_SUBJECTS', subjects)
  },
  updateGrades({ commit }, grades) {
    commit('SET_GRADES', grades)
  },
  updateChannels({ commit }, channels) {
    commit('SET_CHANNELS', channels)
  },
  addSubject({ commit }, subject) {
    commit('ADD_SUBJECT', subject)
  },
  addGrade({ commit }, grade) {
    commit('ADD_GRADE', grade)
  },
  addChannel({ commit }, channel) {
    commit('ADD_CHANNEL', channel)
  }
}

const getters = {
  getSubjects: state => state.subjects,
  getGrades: state => state.grades,
  getChannels: state => state.channels
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 